package com.babel.util.util;

import java.util.ArrayList;
import java.util.List;

/**
 * 比较
 * Created by CH on 2017/11/8.
 */
public class Compare<T> {

    /**
     * 过滤
     * [过滤出新增和需要删除的数据]
     * @param source 数据库中的数据列表
     * @param target 传入的数据列表
     * @return
     */
    public Result filter(List<T> source, List<T> target) {
        // 为了不影响原有的数据, 这里克隆list
        List<T> sourceClone = new ArrayList<>();
        sourceClone.addAll(source);
        List<T> targetClone = new ArrayList<>();
        targetClone.addAll(target);

        Result result = new Result();

        if(null == targetClone || targetClone.size() == 0){
            return null;
        }

        if(null == sourceClone || sourceClone.size() == 0){
            List<T> insertList = targetClone;
            result.setInsertList(insertList);
            return result;
        }

        List<T> tempTarget = new ArrayList<>();
        tempTarget.addAll(targetClone);

        targetClone.removeAll(sourceClone);
        List<T> insertList = targetClone;

        sourceClone.removeAll(tempTarget);
        List<T> deleteList = sourceClone;

        tempTarget.removeAll(targetClone);
        List<T> updateList = tempTarget;

        result.setInsertList(insertList);
        result.setDeleteList(deleteList);
        result.setUpdateList(updateList);
        return result;
    }

    /**
     * 比较结果
     */
    public class Result {

        /**
         * 新增数据列表
         */
        private List<T> insertList = new ArrayList<T>();

        /**
         * 需删除的数据列表
         */
        private List<T> deleteList = new ArrayList<T>();

        /**
         * 需编辑的数据列表
         */
        private List<T> updateList = new ArrayList<T>();

        public List<T> getInsertList() {
            return insertList;
        }

        public void setInsertList(List<T> insertList) {
            this.insertList = insertList;
        }

        public List<T> getDeleteList() {
            return deleteList;
        }

        public void setDeleteList(List<T> deleteList) {
            this.deleteList = deleteList;
        }

        public List<T> getUpdateList() {
            return updateList;
        }

        public void setUpdateList(List<T> updateList) {
            this.updateList = updateList;
        }

        @Override
        public String toString() {
            return insertList.toString() + "\n" + deleteList.toString();
        }
    }

}

